package spzx.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.product.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import spzx.product.mapper.CategoryMapper;
import spzx.product.service.CategoryService;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<Category> findOneCategoryList(Long parentId) {
        return categoryMapper.findByParentId(parentId);
    }

    @Override
    public List<Category> findCategoryTree(Long pid) {
        List<Category> list = categoryMapper.findByParentId(pid);

        for (Category category : list) {
            category.setChildren(this.findCategoryTree(category.getId()));
        }

        return list;
    }

    @Cacheable(value = "category",key = "'findCategoryTreeByOneSql'")
    //value:缓存的命名空间，不同的命名空间下。存储不同模块的缓存数据；value="category"：表示存储在category命名空间下存储与商品分类相关的缓存数据
    //key:指定了向redis中添加的一组缓存数据的key的格式"'key'"
    //被@Cacheable注解标注的方法，当它被调用时，先不执行方法体内容，而是先从指定的命名空间下(value="category"),查询key=findOneCategoryList(parentId)的缓存数据是否存在，
    //若存在，则直接返回缓存数据，若不存在，则执行方法体内容，并将结果存入redis缓存中，并设置缓存时间为30分钟
    @Override
    public List<Category> findCategoryTreeByOneSql() {
        /*String key = "categoryCache";
        //1.查询redis缓存中是否存在
        String jsonString = stringRedisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(jsonString)){
            System.out.println("读取redis缓存");
            return JSON.parseArray(jsonString, Category.class);
        }*/
        //2.若不存在，读取mysql
        List<Category> oneCategoryList = this.getByMysql();
        /*//3.将结果存入redis缓存
        String value = JSON.toJSONString(oneCategoryList);//转为json字符串
        stringRedisTemplate.opsForValue().set(key, value,30, TimeUnit.MINUTES);*/

        return oneCategoryList;
    }

    private List<Category> getByMysql() {
        System.out.println("读取mysql");
        //1.查询所有分类
        List<Category> allCategory = categoryMapper.findAll();
        //2.从集合中筛选一级分类
        //若当前分类的pid=0，此分类就是目标需要的
        List<Category> oneCategoryList = allCategory.stream().filter(category -> {
            return category.getParentId().longValue() == 0;
        }).collect(Collectors.toList());

        //3.为每个一级分类筛选二级分类
        oneCategoryList.stream().forEach(oneCategory -> {
            List<Category> twoCategoryList = allCategory.stream().filter(category -> {
                return category.getParentId().longValue() == oneCategory.getId();
            }).collect(Collectors.toList());

            //4.为每个二级分类筛选三级分类
            twoCategoryList.stream().forEach(twoCategory -> {
                List<Category> threeCategoryList = allCategory.stream().filter(category -> {
                    return category.getParentId().longValue() == twoCategory.getId();
                }).collect(Collectors.toList());

                twoCategory.setChildren(threeCategoryList);
            });

            oneCategory.setChildren(twoCategoryList);
        });

        return oneCategoryList;
    }
}
